package eo.builder.impl;

import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import eo.builder.URLVisitor;
import eo.builder.util.IterationStep;

/**
 * 
 * @author takeshi
 * 
 */
public abstract class AbstractURLVisitor implements URLVisitor {

	public final List<String> listMatchingResources(URL root, String regex)
			throws IOException {
		final Pattern pattern = Pattern.compile(regex);
		final List<String> results = new LinkedList<String>();
		this.iterate(new IterationStep<String>() {
			public boolean nextIteration(String e) {
				if (pattern.matcher(e).matches()) {
					results.add(e);
				}
				return true;
			}
		}, root);
		return results;
	}

	public final boolean isResourcePresent(final String resourceName, final URL url)
			throws IOException {
		if (resourceName == null || url == null || !this.canResolve(url)) {
			return false;
		}
		final ResultHolder holder = new ResultHolder();
		this.iterate(new IterationStep<String>() {
			public boolean nextIteration(String e) {
				holder.result = resourceName.equals(e);
				return !holder.result;
			}}, url);
		return holder.result;
	}
	
	/**
	 * 
	 * @author takeshi
	 *
	 */
	private static final class ResultHolder {
		private boolean result;
	}
	
}
